<template>

  <NLayout has-sider wh-full>
    <NLayoutSider content-style="padding: 10px;" :collapsed-width="0" :width="650" show-trigger="arrow-circle"
                  style="border-radius: 10px;height: 100%;">
      <n-card size="small" title="日期"  :bordered="false"  >
        <template #header-extra>
          <NSelect
              style="width: 200px;float: right"
              :options="data.option_space"
              clearable
              placeholder="请选择门店"
              v-model:value="data.space_id"
              @update:value="onSpaceChange"
          />&nbsp;
        </template>
        <n-calendar
            v-model:value="selectedDate"
            #="{ year, month, date }"
            :is-date-disabled="isDateDisabled"
            @update:value="handleUpdateValue"
            @panel-change="(panel, value) => handleChange(panel)"
            style="margin:0 10px"
            class="custom-calendar"
        >
          <div style="margin-top:5px">
            <div v-if="getAppointmentCount(year, month, date)">
              预约: {{ getAppointmentCount(year, month, date) }}
            </div>

          </div>

        </n-calendar>
      </n-card>
    </NLayoutSider>
    <NLayoutContent style="background: transparent;border: 0;margin-left:20px">
      <n-card  size="small" title="预约情况" style="height: 100%;">
        <template #header-extra>
          <NButton  type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建预约
          </NButton>
        </template>
        <n-scrollbar x-scrollable style="width: 100%;" trigger="none">
          <n-flex class="tb_row">
            <div class="tb_head">技师姓名</div>
            <div class="tb_head" v-for="item in data.head">{{item}}</div>
          </n-flex>
          <n-flex class="tb_row" v-for="item in data.designers">
            <div class="tb_head">{{item.name}}</div>

            <div class="tb_task" :style="'width:'+item2.width+'px;margin-left:'+item2.left+'px;'" v-for="item2 in item.ap_con" @click="select_customer(item2)">
              <div>{{item2.project_name}}</div>
              <div style="font-size: 12px">{{item2.user_name}}</div>
              <div style="font-size: 10px">{{item2.user_phone}}</div>
              <div style="font-size: 10px">{{item2.extend}}</div>
            </div>
          </n-flex>

        </n-scrollbar>
      </n-card>
        <n-drawer v-model:show="data.show_info" width="50%" placement="right">
      <Info :info-data="data.select_customer"/>
    </n-drawer>
    </NLayoutContent>
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading"
      style="width: 900px !important;" @save="handleSave">

      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm"
        :rules="addAPIRules" :validate-on-rule-change="true">
        <NFlex justify="space-between">
          <NFormItem label="会员昵称" path="user_id">
            <n-select style="width: 300px"
                      v-model:value="modalForm.user_id"
              filterable
              placeholder="搜索会员昵称"
              :options="data.options"
              :loading="data.loading"
              clearable
              remote
              @search="handleSearch"
            />
          </NFormItem>
          <NFormItem label="预约人数" path="come_nums">
            <NInputNumber style="width: 300px;" min="1"  v-model:value="modalForm.come_nums" clearable placeholder="请输入预约人数" />
          </NFormItem>
          <NFormItem label="所属门店" path="space_id">
            <NSelect style="width: 300px; " v-model:value="modalForm.space_id"
              :options="data.option_space" placeholder="请选择所属门店" @change="get_select_designers"/>
          </NFormItem>
<!--          <NFormItem label="选择项目" path="project_ids">-->
<!--            <n-cascader style="width: 300px;" v-model:value="modalForm.project_ids"-->
<!--              multiple-->
<!--              clearable-->
<!--              placeholder="请选择项目"-->
<!--              :options="data.goods_options"-->
<!--              cascade-->
<!--              check-strategy="child"-->
<!--              show-path-->
<!--              filterable-->
<!--              clear-filter-after-select-->
<!--              @update:value="getLongs"-->
<!--            />-->
<!--          </NFormItem>-->
<!--          <NFormItem label="合计时长" path="longs">-->
<!--            <n-input round placeholder="0" v-model:value="modalForm.longs" disabled>-->
<!--              <template #suffix>-->
<!--                分钟-->
<!--              </template>-->
<!--            </n-input>-->
<!--          </NFormItem>-->
          <NFormItem label="预约时间" path="time">
            <n-date-picker v-model:value="modalForm.time"
                 style="width: 300px;"
              v-model:formatted-value="formattedValue"
              value-format="yyyy.MM.dd HH:mm:ss"
              type="datetime"
              clearable
            />
          </NFormItem>
<!--          <NFormItem label="请选择技师" path="designer_ids">-->
<!--            <n-select v-model:value="modalForm.designer_ids" style="width: 300px;" multiple :options="data.select_designers" />-->
<!--          </NFormItem>-->
          <NFormItem label="技师/项目" path="projects">
              <n-layout>
                <n-layout-header>
                  <n-flex >
                    <n-tag size="large" style="width: 300px"> 技师 </n-tag>
                    <n-tag size="large" style="width: 300px"> 项目 </n-tag>
                  </n-flex>
                </n-layout-header>
                <n-layout-content content-style="padding: 10px 0;">
                  <n-dynamic-input v-model:value="modalForm.projects" :on-create="onCreate_gg"  min="1">
                    <template #default="{ value }">
                      <n-flex justify="space-between" >
                        <n-select v-model:value="value.designer_id" style="width: 300px;" :options="data.select_designers" />
                        <n-cascader style="width: 300px;" v-model:value="value.project_id"
                          clearable
                          placeholder="请选择项目"
                          :options="data.goods_options"
                          cascade
                          check-strategy="child"
                          show-path
                          filterable
                          clear-filter-after-select
                        />
                      </n-flex>
                    </template>
                  </n-dynamic-input>
                </n-layout-content>
              </n-layout>
            </NFormItem>
            <NFormItem label="附加信息" path="extend">
              <NInput v-model:value="modalForm.extend" @input="handleInput" clearable placeholder="请填写附加信息" />
            </NFormItem>
        </NFlex>
      </NForm>

    </CrudModal>
  </NLayout>




</template>

<script setup>
import {
  NAvatar,
  NButton,
  NDatePicker, NFlex,
  NForm,
  NFormItem, NInput,
  NLayout,
  NLayoutContent,
  NLayoutSider,
  NSelect,
  NTag
} from 'naive-ui';
import { useMessage } from 'naive-ui'
import CommonPage from "@/components/page/CommonPage.vue";
import {onMounted,ref} from "vue";
import api from "@/api";
import TheIcon from "@/components/icon/TheIcon.vue";
import Info from "@/views/customer/user/info.vue";
import {useCRUD} from "@/composables";
import default_image from "@/assets/images/mz.jpg";
import CrudModal from "@/components/table/CrudModal.vue";
const message = useMessage()
const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '预约',
  initForm: {},
  doCreate: api.createAppointmentList,//接口地址修改
  refresh: () => refresh_new(),
})
function handleUpdateValue(e) {
  const date = new Date(e);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');  // 月份从0开始，需加1并补充0
  const day = String(date.getDate()).padStart(2, '0');  // 补充0确保两位数字
  const formattedDate = `${year}-${month}-${day}`;
  data.select_date = formattedDate
  get_appointment()
}

function refresh_new(){
  re_load()
}


const onCreate_gg = () => {
  return {
    designer_id: '',
    project_id: '',
  }
}

const appointmentMap = ref({})
const data = reactive({
  designers:[],
  head:[],
  space_id:1,
  option_space:[],
  select_date:"",
  select_month:"",
  month3data:[],
  select_customer:{
    id:0,
    name:"暂未选择",
    phone:"x",
    money_deposit:0
  },
  show_info:false,
  loading: false,
  options:[],
  goods_options:[],
  select_designers:[],
  project_id:0,
  ex_project_ids:0,
  longs:0
});
const addAPIRules = {
}

onMounted(() => {
  api.getSpaceList().then((res) => {
    data.option_space = res.data
    data.space_id = res.data[0].value
    modalForm.value.space_id = res.data[0].value
    re_load()
  })
  api.getSelectProject({
    category_id: 1,
    space_id:data.space_id
  }
  ).then((res) => {
    data.goods_options = res.data
  })
  get_select_designers()
})



function onSpaceChange(){
  message.success("切换门店")
  re_load()
}

function re_load(){
  get_3month()
  get_appointment()
}

function handleSearch(query){
  if (!query.length) {
    data.options = [];
    return;
  }
  data.loading = true;
  window.setTimeout(async () => {
    await api.getSaasUserList({
      name: query
    }).then((res) => {
      data.options = res.data
    })
    data.loading = false;
  }, 1e3);
}

function get_appointment(){
  api.getAllAppointment({
    date: data.select_date,
    space_id:data.space_id
  }).then((res) =>{
    data.head = res.data.head
    data.designers = res.data.list
  })
}
function get_select_designers(){
  api.getSettingDesigner({
    space_id:modalForm.value.space_id,
  }).then((res) => {
      data.select_designers = res.data
  })
}

function handleChange(panel){
  console.log(panel)
  let year = panel.year
  let month = panel.month
  if(month<10){
    data.select_month =year+"-0"+month
  }else{
    data.select_month =year+"-"+month
  }
  get_3month()
}

function get_3month(){
  api.get3MonthAppointment({
    month:data.select_month,
    space_id:data.space_id
  }).then((res) => {
    data.month3data = res.data

    const map = {};
    res.data.forEach((item) => {
      map[item.date] = item.nums;
    });
    appointmentMap.value = map;

  })
}


// 根据日期获取预约数量
const getAppointmentCount = (year, month, date) => {
  const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`;
  if(appointmentMap.value[dateStr]>0){
    console.log("取得预约"+appointmentMap.value[dateStr])
  }
  return appointmentMap.value[dateStr] || 0;
};

function handleInput(e) {
  this.modalForm.extend = e.target.value.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/g, '');
}

function select_customer(item){
  message.success('已选择客户:'+item.user_name)
  data.select_customer.id = item.user_id
  data.show_info = true

}


function get_customer_detail(){
  api.getSaasUserDetail({
    id:data.select_customer.id
  }).then((res) => (data.select_customer = res.data))

  data.select_coupons = []
  api.getSaasUserCouponsList({
    user_id:data.select_customer.id
  }).then((res) => (data.coupons = res.data))
}

</script>
<style>
.custom-calendar {
  width: 100%;  /* 设置每个日期格子的宽度 */
  height: 400px;  /* 设置每个日期格子的高度 */
}
.tb_row{
  margin-bottom: 5px;
  gap:0px !important;
  width: 2200px;
  border:1px solid #eee;
  padding: 5px;
}
.tb_head{
  width:80px;
  text-align: center;
  border-right:1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}
.tb_task{
  min-width: 80px;
  background: #8945c3;
  color:white;
  text-align: center;
  border-radius: 5px;
  margin:2px;
}
</style>